package code;

import java.util.*;

public class GetPassword_day10_shenxinfu {
    public static class LinkNode{
        public LinkNode(int key,int next_position){
            this.key = key;
            this.next_position=next_position;

        }
        int key;
        int next_position;

        public int getKey() {
            return key;
        }

        public void setKey(int key) {
            this.key = key;
        }

        public int getNext_position() {
            return next_position;
        }

        public void setNext_position(int next_position) {
            this.next_position = next_position;
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n=Integer.parseInt(sc.nextLine());
        for(int i=1;i<=n;i++){
            int m= Integer.parseInt(sc.nextLine());
            int[] arr=new int[m];
            LinkNode head;
            List<LinkNode> list= new ArrayList<>();
            for(int j=1;j<=m;j++){
               String nums=sc.nextLine();
               String[] temp=nums.split(" ");
               list.add(new LinkNode(Integer.parseInt(temp[0]),Integer.parseInt(temp[1])));
            }
            GetPassword(list);
        }
    }
    public static void GetPassword(List<LinkNode> list){
        Deque<LinkNode> deque=new ArrayDeque<>();
        //找到
        deque.addLast(list.get(0));
        int next=list.get(0).getNext_position();
        int i;
        for(i=0;i<list.size();i++){
            if(next==0){
                break;
            }
            deque.addLast(list.get(next-1));
            next=list.get(next-1).getNext_position();

        }
        deque.addLast(list.get(next));
        next=i+1;
        for(;i<list.size();i++){

            deque.addFirst(list.get(next-1));
            next=list.get(next-1).getNext_position();

        }
        for(i=0;i<=list.size();i++){
            System.out.print(deque.pop().getKey()+" ");
        }

    }
}
